let currentPage = 1;
let pageSize = 12;
let currentStatus = '';

window.onload = function () {
  fetchResumes(currentPage, pageSize, currentStatus);
  const searchButtons = document.querySelectorAll('.search-btn');
  searchButtons.forEach(button => {
    button.addEventListener('click', function () {
      const college = document.getElementById('college-keyword').value;
      const major = document.getElementById('major-keyword').value;
      const name = document.getElementById('name-keyword').value;
      fetchResumes(1, pageSize, currentStatus, college, major, name);
    });
  });

  const statusButtons = document.querySelectorAll('.nav-button');
  statusButtons.forEach(function (button) {
    button.addEventListener('click', function () {
      const statusText = this.dataset.tabId;
      const statusCode = getStatusFromButton(this);
      currentStatus = statusCode;
      const college = document.getElementById('college-keyword').value;
      const major = document.getElementById('major-keyword').value;
      const name = document.getElementById('name-keyword').value;
      fetchResumes(1, pageSize, statusCode, college, major, name);
      switchTab(statusText);
    });
  });

  const chooseModuleBtn = document.getElementById('scrollToChooseModuleBtn');
  if (chooseModuleBtn) {
    chooseModuleBtn.addEventListener('click', function () {
      const statusText = this.dataset.tabId;
      const statusCode = getStatusFromButton(this);
      currentStatus = statusCode;
      const college = document.getElementById('college-keyword').value;
      const major = document.getElementById('major-keyword').value;
      const name = document.getElementById('name-keyword').value;
      fetchResumes(1, pageSize, statusCode, college, major, name);
      switchTab(statusText);
    });
  }
};

function fetchResumes(page, pageSize, status = '', college = '', major = '', name = '') {
  const url = `http://192.168.244.14:8080/users/status?page=${page}&pagesize=${pageSize}&status=${status}&college=${college}&major=${major}&name=${name}`;
  fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error('网络响应错误：' + response.status);
      }
      return response.json();
    })
    .then(data => {
      console.log('Response data:', data);
      if (data && data.code === 1) {
        displayResumes(data.data.rows, page);
        updatePagination(data.data.total, page);
      } else {
        alert('获取简历失败：' + (data && data.msg ? data.msg : '未知错误'));
      }
    })
    .catch(error => {
      console.error('获取简历请求出错:', error);
      alert('获取简历请求出错');
    });
}

function displayResumes(resumeData, page) {
  console.log('Displaying resumes for page:', page, 'Data:', resumeData);
  var resumeList = document.getElementById('resumeList');
  if (!resumeList) {
    console.error('未找到 resumeList 元素');
    return;
  }
  resumeList.innerHTML = '';
  var startIndex = (page - 1) * 12 + 1;
  console.log(startIndex);
  resumeData.forEach(function (resume, index) {
    try {
      console.log('Processing resumes:', resume);
      var listItem = document.createElement('li');
      let statusText;
      switch (resume.status) {
        case 0:
          statusText = '未投递';
          break;
        case 1:
          statusText = '已投递';
          break;
        case 2:
          statusText = '已查看';
          break;
        case 3:
          statusText = '已通过';
          break;
        case 4:
          statusText = '未通过';
          break;
        default:
          statusText = '未知状态';
      }
      var currentIndex = startIndex + index;
      console.log(currentIndex);
      listItem.innerHTML = `
              <span>${currentIndex}</span>
              <span>${resume.name}</span>
              <span>${resume.major}</span>
              <span>${resume.college}</span>
              <span>${statusText}</span>
              <button onclick="viewResume('${resume.id}')">查看简历</button>
          `;
      resumeList.appendChild(listItem);
    } catch (error) {
      console.error('处理简历数据时出错:', error, '简历数据:', resume);
    }
  });
}

function switchTab(status) {
  document.querySelectorAll('.nav-button').forEach(btn => {
    btn.classList.remove('active');
  });

  const activeButton = document.querySelector(`.nav-button[data-tab-id="${status}"]`);
  if (activeButton) {
    activeButton.classList.add('active');
  }
}

function updatePagination(total, page) {
  var pagination = document.getElementById('pagination');
  pagination.innerHTML = '';
  var totalPages = Math.ceil(total / 12);
  for (var i = 1; i <= totalPages; i++) {
    var button = document.createElement('button');
    button.textContent = i;
    if (i === page) {
      button.classList.add('active');
    }
    button.addEventListener('click', function () {
      const college = document.getElementById('college-keyword').value;
      const major = document.getElementById('major-keyword').value;
      const name = document.getElementById('name-keyword').value;
      fetchResumes(parseInt(this.textContent), 12, currentStatus, college, major, name);
    });
    pagination.appendChild(button);
  }
}

function viewResume(userId) {
  localStorage.setItem('userId', userId);
  fetch(`http://192.168.244.14:8080/resumeStatus/read?usersId=${userId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(response => {
      if (!response.ok) {
        throw new Error('网络响应错误：' + response.status);
      }
      return response.json();
    })
    .then(data => {
      if (data && data.code === 1) {
        window.location.href = 'http://127.0.0.1:5501/sparkResume/html/manager-choose.html';
      }
    })
    .catch(error => {
      console.error('修改简历状态请求出错:', error);
      alert('修改简历状态请求出错，请检查网络连接');
    });
}
function getStatusFromButton(button) {
  const dataTabId = button.getAttribute('data-tab-id');
  switch (dataTabId) {
    case '已投递':
      return '1';
    case '已查看':
      return '2';
    case '已通过':
      return '3';
    case '未通过':
      return '4';
    default:
      return '';
  }
}